package com.toolbox.controller;

import com.toolbox.service.TranslationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/tools/text")
public class TranslationController {

    private static final Logger logger = LoggerFactory.getLogger(TranslationController.class);
    
    @Autowired
    private TranslationService translationService;

    /**
     * 文本翻译接口
     * @param request 请求参数，包含sourceText和targetLanguage
     * @return 翻译结果
     */
    @PostMapping("/translate")
    public ResponseEntity<?> translateText(@RequestBody Map<String, String> request) {
        
        try {
            // 获取请求参数
            String sourceText = request.get("sourceText");
            String targetLanguage = request.get("targetLanguage");
            
            logger.debug("翻译请求参数 - 源文本: {}, 目标语言: {}", sourceText, targetLanguage);
            
            // 参数验证
            if (sourceText == null || sourceText.trim().isEmpty()) {
                Map<String, String> errorMap = new HashMap<>();
                errorMap.put("error", "请输入要翻译的文本");
                return ResponseEntity.badRequest().body(errorMap);
            }
            
            if (targetLanguage == null || targetLanguage.trim().isEmpty()) {
                Map<String, String> errorMap = new HashMap<>();
                errorMap.put("error", "请选择目标语言");
                return ResponseEntity.badRequest().body(errorMap);
            }
            
            // 调用服务层进行翻译
            String translatedText = translationService.translateText(sourceText, targetLanguage);
            logger.info("翻译完成，结果: {}", translatedText);
            
            // 返回翻译结果
            Map<String, String> resultMap = new HashMap<>();
            resultMap.put("translatedText", translatedText);
            return ResponseEntity.ok(resultMap);
            
        } catch (IllegalArgumentException e) {
            logger.warn("翻译请求参数错误: {}", e.getMessage());
            Map<String, String> errorMap = new HashMap<>();
            errorMap.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(errorMap);
        } catch (Exception e) {
            logger.error("翻译过程中发生错误: {}", e.getMessage(), e);
            Map<String, String> errorMap = new HashMap<>();
            errorMap.put("error", "翻译失败，请稍后重试");
            return ResponseEntity.internalServerError().body(errorMap);
        }
    }
}